<template>
  <div class="create-order">
    <div style="position: relative; flex: 1">
      <div class="match" v-if="orderData?.match">
        <div class="header">
          <template v-if="orderData.type == 0">
            <div class="title">注单（{{ orderInfo.count || 0 }}）</div>
            <div class="money">{{ orderInfo.totalAmount || 0 }} RMB</div>
          </template>
          <template v-if="orderData.type == 1">
            <div class="title">预约（{{ orderInfo.count || 0 }}）</div>
            <div class="money">RMB</div>
          </template>
          <template v-if="orderData.type == 2">
            <div class="title">口报（{{ orderInfo.count || 0 }}）</div>
            <div class="money">RMB</div>
          </template>

          <div class="btn-delete" @click="store.clear">
            <img src="@/assets/board/out/del.png" />
          </div>
        </div>

        <div style="
            height: 76px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 0 16px;
            border-bottom: 1px solid #ebebeb;
          ">
          <div>
            <div class="info">
              <div class="type">
                {{ orderData.match != null && orderData.match.sport_type == 'basketball' ? '篮球' : '足球' }}
              </div>
              <div class="match-name">/{{ orderData?.match?.league_name }}</div>
            </div>
            <div class="pk" v-if="orderData?.match">
              <div class="pk-item">{{ orderData?.match?.home_name }}</div>
              <div class="vs"></div>
              <div class="pk-item">{{ orderData?.match?.away_name }}</div>
            </div>
          </div>
        </div>
      </div>

      <el-scrollbar height="calc( 100vh - 300px )">
        <OrderData @changeShortcut="handleSubmit" />
      </el-scrollbar>
      <div class="footer">
        <div class="btn-submit" @click="handleSubmit" ref="submitRef">下单</div>
      </div>

      <UserDialog v-if="state.userdialogshow.show" v-model="state.userdialogshow.show" />
    </div>

    <DetailedList v-model="createorderdialog" @change="changeform" :data="createorderData"
      :detailedType="detailedType" />
  </div>
</template>
<script setup>
import { http } from '@/utils/http'
import { ElMessage } from 'element-plus'
import { provide } from 'vue'
import OrderData from './OrderData.vue'
import UserDialog from './UserDialog.vue'
import Tab from './Tab.vue'

import DetailedList from './DetailedList.vue'

const { store, state } = inject('Sell')
const { orderData } = state

provide('orderData', orderData)

const createorderdialog = ref(false)
const submitRef = ref(null)
// 出货清单数据
const createorderData = ref({
  type: 0,
  dataobj: {},
  dataarr: [],
})

const detailedType = ref(0)

const orderList = computed(() => {
  return state.orderData.type == 0 ? state.orderData.list : state.orderData.reservationList
})

const orderInfo = computed(() => {
  const data = {
    totalAmount: 0,
    count: 0,
  }

  Object.keys(orderList.value).map(key => {
    const orders = orderList.value[key]

    orders.map(item => {
      if (item.checked) {
        data.totalAmount += Number(item.stake)
        data.count++
      }
    })
  })

  return data
})

const handleSubmit = () => {

  const { orderData, userId } = state

  const { match } = orderData
  if (match) {


    let data = []

    const body = {
      minfo: {
        sport_type: match.sport_type,
        event_type: match.event_type,
        league_id: match.league_id,
        league_name: match.league_name,
        home_id: match.home_id,
        home_name: match.home_name,
        away_id: match.away_id,
        away_name: match.away_name,
        match_time: match.match_time,
        match_time_stamp: match.match_time_stamp,
      },
      place_data: [],
      sport_type: match.sport_type,
      event_type: match.event_type,
      user_config_id: userId,
      total_stake: 0,
      score: {
        score: match.score == '' ? '0:0' : match.score,
        half_score: match.half_score ? match.red_card : '0:0',
        red_card: match.red_card == '' ? '0:0' : match.red_card,
        yellow_card: match.yellow_card == '' ? '0:0' : match.yellow_card,
        corner: match.corner == '' ? '0:0' : match.corner,
      },
    }
    let body2 = JSON.parse(JSON.stringify(body))
    console.log(orderList.value)

    Object.keys(orderList.value).map(key => {
      const orders = orderList.value[key]
      console.log(orders);
      let body3 = JSON.parse(JSON.stringify(body))
      orders.map(item => {
        if (item.checked) {
          body3.total_stake += Number(item.stake)
          let pkoddskeyarr = item.pk_odds_key.split(':')
          pkoddskeyarr[pkoddskeyarr.length - 2] = item.pk_ratio
          body3.minfo.bc_type = item.bc_type

          let a = {
            pk_odds_key: pkoddskeyarr.join(':'),
            bc_type: item.bc_type,
            league_id: item.league_id,
            home_id: item.home_id,
            away_id: item.away_id,
            nav_data: item.nav_data,
            odd: item.odd,
            user_id: item.userId,
            pk_odds_key_ch: item.pk_odds_key_ch.replace(/-?\d*\.?\d+/g, item.pk_ratio),
            reservation: item.reservation || 0,
            min_odd: parseFloat(item.min_odd).toFixed(2) || 0,
            max_odd: parseFloat(item.max_odd) || 0,
            reservation_pk_ratio: item.pk_ratio || 0,
            reservation_stake: Number(item.reservation_stake) || 0,
            order_mode: item.order_mode,
            place_mode: item.place_mode,
            runtime: item.runtime,
            min_stake: item.min_stake,
            max_stake: item.max_stake,
            // member_count: item.member_count,
            money_mode: (item.order_mode == 'all_user' || item.order_mode == 'count_user') && item.place_mode == 1 ? item.money_mode : 'max'
          }

          if (item.user_id_list && item.user_id_list.length > 0) {
            a.user_id_list = item.user_id_list
          }

          if (item.directionorder) {
            a.user_config_id = item.user_config_id

            body3.place_data.forEach(item2 => {
              if (item.bc_type == item2.bc_type) {
                item2.reverse_order = a
              }
            });
          } else {
            body3.place_data.push(a)
          }


        }
      })

      console.log(body3);
      data.push(body3)

    })
    if (body2.place_data.length) data.push(body2)
    if (localStorage.isDev) {
      ElMessage.warning('测试下单成功')
      return
    }

    let stoporder = false
    data.forEach(item => {
      if (item.place_data.length == 0) {
        stoporder = true
      }
    });

    if (!stoporder) {
      createorderData.value.type = 1
      detailedType.value = 1
      createorderData.value.dataarr = data
      createorderdialog.value = true
    } else {
      ElMessage.warning('请选择下单平台')
      return
    }

  }
}

const createOrder = body => {
  http.post('/orderplacetask/creat_place_order', body).then(res => {
    ElMessage.success(res.msg || '下单成功')
  })
}

const createReservationOrder = () => {
  const { orderData, userId } = state

  const { match } = orderData
  const data = []

  Object.keys(orderList.value).map(key => {
    const body = {
      minfo: {
        sport_type: match.sport_type,
        event_type: match.event_type,
        league_id: match.league_id,
        league_name: match.league_name,
        home_id: match.home_id,
        home_name: match.home_name,
        away_id: match.away_id,
        away_name: match.away_name,
        match_time: match.match_time,
        match_time_stamp: match.match_time_stamp,
      },
      place_data: [],
      sport_type: match.sport_type,
      event_type: match.event_type,
      user_config_id: userId,
      total_stake: 0,
      score: {
        score: match.score == '' ? '0:0' : match.score,
        half_score: match.half_score ? match.red_card : '0:0',
        red_card: match.red_card == '' ? '0:0' : match.red_card,
        yellow_card: match.yellow_card == '' ? '0:0' : match.yellow_card,
        corner: match.corner == '' ? '0:0' : match.corner,
      },
    }

    const orders = orderList.value[key]

    orders.map(item => {
      if (item.checked) {
        body.total_stake += Number(item.stake)
        let a = {
          pk_odds_key: item.pk_odds_key,
          pk_odds_key_ch: item.pk_odds_key_ch,
          bc_type: item.bc_type,
          league_id: item.league_id,
          home_id: item.home_id,
          away_id: item.away_id,
          nav_data: item.nav_data,
          odd: item.odd,
          user_id: item.userId,
          stake: Number(item.stake),

          reservation: item.reservation || 0,
          // reservation_odd: item.reservation_odd || 0,
          min_odd: item.min_odd || 0,
          max_odd: item.max_odd || 0,
          reservation_pk_ratio: item.reservation_pk_ratio || 0,
          reservation_stake_type: item.reservation_stake_type || 0,
          reservation_stake: item.reservation_stake || 0,
          before_timer_min: item.before_timer_min || 0,
          before_timer_max: item.before_timer_max || 0,
          is_ing_timer: item.is_ing_timer || 0,
          ing_timer_max: item.ing_timer_max || 0,
          ing_timer_min: item.ing_timer_min || 0,
          score: match.score,
        }
        if (item.is_superior_place != undefined && item.is_superior_place != null) {
          a.is_superior_place = item.is_superior_place
        } else {
          a.is_superior_place = 0
        }
        body.place_data.push(a)
      }
    })

    if (body.place_data.length) data.push(body)
  })

  if (data.length == 0) {
    ElMessage.warning('请先勾选')
    return
  }
  console.log(data)

  if (data.length > 1 || data[0].place_data.length > 1) {
    createorderData.value.type = 1
    detailedType.value = 0
    createorderData.value.dataarr = data
    createorderdialog.value = true
  } else {
    http.post('/order/creat_reservation_order', data).then(res => {
      ElMessage.success(res.msg || '下单成功')
    })
  }
}

const changeform = data => {
  let list = JSON.parse(JSON.stringify(state.orderData.reservationList))
  let a = []
  data.forEach(item => {
    item.place_data.forEach(item2 => {
      a.push(item2)
    })
  })
  let c = []
  a.forEach(item => {
    let pk_odds_key = item.pk_odds_key
    state.orderData.list[pk_odds_key]
    const index = list[pk_odds_key].findIndex(obj => obj.bc_type === item.bc_type)

    // 如果找到了对应的对象，删除它
    if (index !== -1) {
      list[pk_odds_key].splice(index, 1)
      if (list[pk_odds_key].length == 0) {
        delete list[pk_odds_key]
      }
    }
  })
  state.orderData.reservationList = list
}

const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !createorderdialog.value) {
    const tagName = event.target.tagName.toLowerCase();
    if (['input', 'textarea', 'select'].includes(tagName)) {
      return;
    }
    event.preventDefault();

    setTimeout(() => {
      handleSubmit()
    }, 100);


  }
}

onMounted(() => {
  window.addEventListener('keydown', handleKeyPress);
})
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyPress);
});
</script>
<style lang="scss" scoped>
.create-order {
  width: 496px;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px 0 0 16px;
  background: #fff;
}

.header {
  height: 60px;
  padding: 8px 16px;
  background-color: #fff4ec;
  display: flex;
  flex-direction: column;
  position: relative;

  .title {
    font-size: 16px;
    font-weight: 600;
    line-height: 1.56;
    color: #333;
  }

  .money {
    font-size: 14px;
    font-weight: 600;
    color: #333;
  }

  .btn-delete {
    position: absolute;
    top: 50%;
    right: 16px;
    width: 20px;
    height: 20px;
    margin-top: -10px;
  }
}

.match {
  // padding: 16px;

  .info {
    display: flex;
    height: 24px;
    align-items: center;

    .type {
      height: 24px;
      margin-right: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #282828;
      background: url('@/assets/board/out/football.png') no-repeat 0 center;
      padding-left: 28px;
    }

    .tag {
      height: 20px;
      display: flex;
      align-items: center;
      padding: 0 4px;
      border-radius: 4px;
      background-color: rgba(71, 172, 255, 0.1);
      color: var(--pcmain-color);
      font-size: 12px;
    }
  }

  .match-name {
    font-size: 12px;
    color: #8a8a8a;
  }
}

.pk {
  display: flex;
  font-size: 16px;
  font-weight: 600;
  color: #282828;
  margin-top: 8px;
  // border-bottom: 1px solid #ebebeb;
  // padding-bottom: 12px;
  // margin-bottom: 12px;
  align-items: center;

  .vs {
    margin: 0 8px;
    width: 16px;
    height: 16px;
    background: url('@/assets/vs.png') no-repeat 0 center;
    background-size: cover;
  }
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}

.btn-submit {
  width: 100%;
  background-color: var(--pcmain-color);
  line-height: 46px;
  text-align: center;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
}

:deep(.el-dialog) {
  padding: 0;
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    display: none;
  }
}
</style>

<style>
.group_select .el-select__wrapper {
  min-height: 26px;
}
</style>